package com.xiaoqi.store.controller;

import com.xiaoqi.store.entity.CartEntity;
import com.xiaoqi.store.entity.CartVO;
import com.xiaoqi.store.entity.JsonResult;
import com.xiaoqi.store.exception.ServiceException;
import com.xiaoqi.store.exception.impl.*;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author Rookie Coder
 * @Description 基类控制器，存放一些经常会用到的业务方法
 * @Date
 **/
public class BaseController {

    /*
    * @Author xiaoqi
    * @Description  状态码
    * @return int
    **/
    public static final  int OK = 200;

    /*
    * @Author xiaoqi
    * @Description  获取session中的uid
    * @return Integer
    **/
    protected final Integer getUidFromSession(HttpSession session){
     return  Integer.valueOf(session.getAttribute("uid").toString());

    }
    /*
    * @Author xiaoqi
    * @Description  从session中获取用户名
    * @return String
    **/
    protected final  String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }

    /*
    * @Author xiaoqi
    * @Description  从session中获取用户购物车
    * @return
    **/
    protected final List<CartVO> getUserCartFromSession(HttpSession session){
       return (List<CartVO>) session.getAttribute("AllUserCart");

    }


    /*
    * @Author xiaoqi
    * @Description  统一处理所有的异常
    * @return
    **/
    @ExceptionHandler({ServiceException.class})
    public JsonResult<Void> handlerException(Throwable e){
            JsonResult<Void> jsonResult = new JsonResult<>();
            // 用户名重复异常
            if (e instanceof UsernameDuplicateException){
                jsonResult.setState(4000);
                jsonResult.setMessage("用户名重复");
            }
            // 用户名找不到异常
            if (e instanceof UserNotFondException){
                jsonResult.setState(4001);
                jsonResult.setMessage("找不到该用户名");
            }
            // 用户密码错误异常
            if (e instanceof UserPasswordException){
                jsonResult.setState(4002);
                jsonResult.setMessage("用户名密码错误");
            }
            // 用户已存在异常
            if (e instanceof UserHasBeanDelete){
                jsonResult.setState(4003);
                jsonResult.setMessage("用户已存在");
            }
            // 注册用户异常
            if (e instanceof InsertException){
                jsonResult.setState(4004);
                jsonResult.setMessage("用户注册错误");
            }
            if (e instanceof ProductNotFoundException){
                jsonResult.setState(4006);
                jsonResult.setMessage("该商品已下架");
            }
            return  jsonResult;

    }


}
